package cn.edu.jju.stepcounter2.main;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.Toast;

import com.squareup.leakcanary.RefWatcher;

import org.xutils.ex.DbException;
import org.xutils.x;

import java.util.Calendar;

import cn.edu.jju.stepcounter2.R;
import cn.edu.jju.stepcounter2.SCApp;
import cn.edu.jju.stepcounter2.bean.DayData;
import cn.edu.jju.stepcounter2.chart.ChartActivity;
import cn.edu.jju.stepcounter2.main.presenter.MainPresenter;
import cn.edu.jju.stepcounter2.main.presenter.MainPresenterImpl;
import cn.edu.jju.stepcounter2.main.view.MainView;
import cn.edu.jju.stepcounter2.service.AlarmService;
import cn.edu.jju.stepcounter2.service.StepCountService;
import cn.edu.jju.stepcounter2.user.UserActivity;
import cn.edu.jju.stepcounter2.utils.AppManager;
import cn.edu.jju.stepcounter2.utils.GetDate;
import cn.edu.jju.stepcounter2.utils.SPUtils;
import cn.edu.jju.stepcounter2.utils.ShowToastUtil;

import static android.util.Log.i;

public class MainActivity extends AppCompatActivity implements MainView,View.OnClickListener {


    private FrameLayout fl_main;
    private ViewPager vp_main;
    private MainPresenter mainPresenter;
    private long oldClickTime;
    ImageButton ib_theme;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (SPUtils.get(this,"theme","1").equals("1")){
            setTheme(R.style.AppTheme);

        }else {
            setTheme(R.style.AppThemeDark);
        }
        setContentView(R.layout.activity_main);
        ib_theme = (ImageButton) findViewById(R.id.ib_theme);
        if (SPUtils.get(this,"theme","1").equals("1")){
            ib_theme.setBackgroundResource(R.drawable.btn_wave_day);

        }else {
            ib_theme.setBackgroundResource(R.drawable.btn_wave_night);

        }
        ib_theme.setOnClickListener(this);


        vp_main = (ViewPager) findViewById(R.id.vp_main);
        if (SPUtils.get(this, "date", "1").equals("1")) {
            SPUtils.put(this, "date", GetDate.get());
            SPUtils.put(this, "age", "22");
            SPUtils.put(this, "expectStep", "5000");
            SPUtils.put(this, "height", "172");
            SPUtils.put(this, "weight", "60");
            SPUtils.put(this, "sex", "1");
            SPUtils.put(this, "speed", "1.25");
            DayData dayData = new DayData();
            dayData.setCalConsume("0");
            dayData.setSteps("0");
            dayData.setDate(GetDate.get());
            dayData.setExpectStep("5000");

            try {
                x.getDb(SCApp.daoConfig).saveBindingId(dayData);
            } catch (DbException e) {
                e.printStackTrace();
            }
            startDayAlarm();
        } else if (!SPUtils.get(this, "date", "1").equals(GetDate.get())) {
            SPUtils.put(this, "date", GetDate.get());
            DayData dayData = new DayData();
            dayData.setCalConsume("0");
            dayData.setSteps("0");
            dayData.setDate(GetDate.get());
            dayData.setExpectStep((String) SPUtils.get(this, "expectStep", "5000"));
            startDayAlarm();
            try {
                x.getDb(SCApp.daoConfig).saveBindingId(dayData);
            } catch (DbException e) {
                e.printStackTrace();
            }


        }
        startService(new Intent(this, StepCountService.class));

        mainPresenter = new MainPresenterImpl(this);
        mainPresenter.setViewPager();
        registerReceiver(broadcastReceiver, new IntentFilter("update"));
        registerReceiver(newDayReceiver, new IntentFilter("newDay"));

    }

    private void startDayAlarm() {
        Calendar alarmDate = Calendar.getInstance();
        alarmDate.set(alarmDate.get(Calendar.YEAR), alarmDate.get(Calendar.MONTH), alarmDate.get(Calendar.DAY_OF_MONTH) + 1, 0, 0, 0);
        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        Intent intent = new Intent(this, AlarmService.class);
        PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, alarmDate.getTimeInMillis(), 24 * 3600 * 1000, pendingIntent);


    }


    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            i("@@@", "onReceive" + "i");
            mainPresenter.nortifyVPChange();
        }
    };
    private BroadcastReceiver newDayReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            mainPresenter.newVpContent();
            i("@@@@", "new" + "newday");
        }
    };


    public void userCenter(View view) {
        startActivity(new Intent(this, UserActivity.class));


    }

    public void chart(View view) {
        startActivity(new Intent(this, ChartActivity.class));
    }



    @Override
    public ViewPager getViewpager() {
        return vp_main;
    }

    @Override
    public View getViewPgerContent() {
        return getLayoutInflater().inflate(R.layout.layout_show, null);
    }


    @Override
    protected void onRestart() {
        super.onRestart();
        mainPresenter.nortifyVPChange();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        unregisterReceiver(broadcastReceiver);
        unregisterReceiver(newDayReceiver);
        RefWatcher refWatcher = SCApp.getRefWatcher(this);
        refWatcher.watch(this);

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
            case KeyEvent.KEYCODE_ESCAPE:
                if (System.currentTimeMillis() - oldClickTime > 2000) {
                    ShowToastUtil.showToast(this, "再点击一次退出程序");
                    oldClickTime = System.currentTimeMillis();
                } else finish();

                break;

        }
        return true;
    }

    @Override
    public void onClick(View v) {
         switch (v.getId()){
                     case R.id.ib_theme:
                         if (SPUtils.get(this,"theme","1").equals("1")){
                             SPUtils.put(this,"theme","0");
                             this.recreate();


                         }else {
                             SPUtils.put(this,"theme","1");
                             this.recreate();

                         }

                        break;
                     default:
                         break;
                 }

    }
}
